package com.horoscope.astrology.zodiac.signs.free.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.work.WorkManager
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.adapter.RelationAdapter
import com.horoscope.astrology.zodiac.signs.free.bean.RelationResultBean
import com.horoscope.astrology.zodiac.signs.free.bean.UserBean
import com.horoscope.astrology.zodiac.signs.free.infc.OnItemClickedListener
import com.horoscope.astrology.zodiac.signs.free.network.NetworkEngine
import com.horoscope.astrology.zodiac.signs.free.network.NetworkListener
import com.horoscope.astrology.zodiac.signs.free.utils.*
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_business.ADRewardManager
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.activity_relation_result.*
import kotlinx.android.synthetic.main.back_title.*
import kotlinx.android.synthetic.main.item_loading.*
import kotlinx.android.synthetic.main.item_share.*
import kotlinx.android.synthetic.main.view_network_error.*
import kotlinx.coroutines.*

class RelationResultActivity : Base2Activity() {

    private lateinit var mRecyclerView1: RecyclerView
    private lateinit var mAdapter: RelationAdapter

    private var user1: UserBean? = null
    private var user2: UserBean? = null
    private var job: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        immersionWhite()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_relation_result)
        initTitleBar(
            this@RelationResultActivity,
            R.id.btn_back_edit_name,
            R.id.text_view_back_title,
            getString(R.string.label_result)
        )
        text_view_back_title.setTextColor(Color.BLACK)
        btn_back_edit_name.setImageResource(R.drawable.icon_back_black)

        initView()
        request()
        activityShowAd("Interstitial_Relationship")

        AppSettingManager.saveInt(1, "relation_result") // 成功使用了双人匹配
    }

    private fun initView() {
        user1 = intent.getSerializableExtra(USER1) as? UserBean
        user2 = intent.getSerializableExtra(USER2) as? UserBean

        mRecyclerView1 = findViewById(R.id.recycler_two_result)
        mRecyclerView1.addItemDecoration(ItemDecorationToBottom(20))
        mRecyclerView1.layoutManager = LinearLayoutManager(this)
        mAdapter = RelationAdapter(this)
        mRecyclerView1.adapter = mAdapter

        mAdapter.setOnItemClickedListener(object : OnItemClickedListener {
            override fun onItemClick(view: View, position: Int, string: String) {
                showLoading()
                // 协程延迟一秒
                job = GlobalScope.launch(Dispatchers.Main) {
                    // 在一个公共线程池中创建一个协程
                    val isShow = ADRewardManager.mInstance.showRewardAD(
                        TYPE, this@RelationResultActivity, position, TYPE
                    )
                    delay((1500L..3000L).random()) // 非阻塞的延迟一秒（默认单位是毫秒）
                    if (isShow) {
                        showLoaded()
                    } else {
                        showLoaded()
                        ToastUtil.showRewardError(this@RelationResultActivity)
                    }
                }

            }
        })

        name1.text = user1!!.name
        name2.text = user2!!.name
        des1.text = StringBuilder("Born ${user1!!.birthday.replace("-", " ")}")
        des2.text = StringBuilder("Born ${user2!!.birthday.replace("-", " ")}")

        ShareManager.initShare(
            this@RelationResultActivity,
            line_left,
            line_right,
            text_view_share,
            image_view_more_share,
            tv_facebook
        )
        tv_try_again?.setOnClickListener {
            startActivity(RelationCompatibilityActivity.generateIntent(this))
        }

        tv_network_ok.setOnClickListener {
            include_error.visibility = View.GONE
            request()
        }
    }

    override fun onResume() {
        super.onResume()
        // 观看视频后刷新指定位置数据
        LiveEventBus.get(TYPE, Int::class.java)
            .observeSticky(
                this@RelationResultActivity,
                Observer<Int?> { t ->
                    t?.let {
                        showLoaded()
                        mAdapter.notifyPositionData(t)
                    }
                })
    }

    companion object {
        const val TYPE = "RewardsVideo_Relationship"
        const val USER1 = "user1"
        const val USER2 = "user2"
        fun generateIntent(
            context: Context, user1: UserBean, user2: UserBean, alarm: Boolean = false,
            workName: String = ""
        ): Intent {
            val intent = Intent(context, RelationResultActivity::class.java)
            intent.putExtra("Alarm", alarm)
            intent.putExtra("workName", workName)
            val bundle = Bundle()
            bundle.putSerializable(USER1, user1)
            bundle.putSerializable(USER2, user2)
            intent.putExtras(bundle)
            return intent
        }
    }

    fun request() {
        if (user1 == null || user2 == null) {
            return
        }
        loading()
        NetworkEngine.getRelationResult(user1!!.name,
            user1!!.birthday,
            user1!!.gender,
            user2!!.name,
            user2!!.birthday,
            user2!!.gender,
            object : NetworkListener<RelationResultBean>() {
                override fun onSuccess(t: RelationResultBean) {
                    loaded()
                    if (t.data.report.size > 0) {
                        tv_text.visibility = View.VISIBLE
                        tv_try_again.visibility = View.VISIBLE
                        include_error.visibility = View.GONE
                        mAdapter.setData(t.data.report)
                        try {
                            if (intent.getBooleanExtra("Alarm", false)) { // 结束任务
                                WorkManager.getInstance(this@RelationResultActivity)
                                    .cancelUniqueWork(intent.getStringExtra("workName"))
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    } else {
                        errorMake()
                    }
                }

                override fun onFailed(t: RelationResultBean) {
                    super.onFailed(t)
                    errorMake()
                }

                override fun onError(e: String?) {
                    super.onError(e)
                    errorMake()
                }
            })
    }

    private fun errorMake() {
        tv_text.visibility = View.GONE
        tv_try_again.visibility = View.INVISIBLE
        include_error.visibility = View.VISIBLE
        loaded()
    }

    private fun loading() {
        root_relation?.visibility = View.INVISIBLE
        frame_layout_loading_bg?.visibility = View.VISIBLE
        loading_out?.visibility = View.VISIBLE
        loading?.startAnimation(MyAnimationUtils.loadingAnimation())
        loading?.visibility = View.VISIBLE
    }

    private fun loaded() {
        root_relation?.visibility = View.VISIBLE
        frame_layout_loading_bg?.visibility = View.INVISIBLE
        loading_out?.visibility = View.INVISIBLE
        loading?.clearAnimation()
        loading?.visibility = View.INVISIBLE
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        user1 = intent?.getSerializableExtra(USER1) as? UserBean
        user2 = intent?.getSerializableExtra(USER2) as? UserBean
        root_relation.fullScroll(ScrollView.FOCUS_UP)
        request()
    }

    override fun onStop() {
        super.onStop()
        job?.cancel() // 取消协程
    }

}
